#!/usr/bin/env node

const Readline = require('readline')
const Chalk = require('chalk')
const Fs = require('fs')
const Path = require('path')

// 同步递归创建目录
function mkdirsSync(dirname, mode) {
    mode = mode || '0775'
    if (Fs.existsSync(dirname)) {
        return true
    } else {
        if (mkdirsSync(Path.dirname(dirname), mode)) {
            Fs.mkdirSync(dirname, mode)
            return true
        }
    }
}

// readline实例
const rl = Readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// 新建模块
let createModule = function () {
    rl.question(Chalk.blue('[HINT:] Please enter the module name：'), module => {
        module = module.toString().trim()
        // 查看模块是否存在
        if (Fs.existsSync(`./src/controller/${module}`)) {
            // 模块已存在
            console.warn(Chalk.yellow('[WARNING:] Module already exists. '))
        } else {
            // 创建模块
            mkdirsSync(`./src/controller/${module}`)
            // 创建模块入口文件
            Fs.writeFileSync(`./src/controller/${module}/index.js`, Fs.readFileSync('./tpl/index.tpl.js', 'utf-8'))

            // 创建模块入口模板
            if (module.indexOf('/') > -1) {
                let parts = module.split('/')
                parts.pop()
                mkdirsSync(`./src/view/${parts.join('/')}`)
            }

            Fs.writeFileSync(`./src/view/${module}.html`, Fs.readFileSync('./tpl/index.tpl.html', 'utf-8'))
            // 提示：已完成创建
            console.log(Chalk.green('[INFO:] All Done. '))
        }

        rl.close()
    })
}

// 提示：输入操作指令
rl.question(Chalk.blue('[HINT:] Please input command: '), answer => {
    answer = answer.toString().trim()
    switch (answer) {
        case 'm':   // 新建模块
            createModule.call()
            break
        default:
            console.log(Chalk.red('[ERROR:] Bad command. '))
            rl.close()
    }
})

// 销毁资源，退出进程
rl.on('close', function () {
    console.log(Chalk.gray('\n[OTHER:] Being quit...'))
    process.exit(0)
})